<template>
    <div>
        <div>
            <template>
                <el-select v-model="formInline.type" clearable placeholder="请选择" size="small" class="selectOption">
                    <el-option
                            v-for="item in options"
                            :key="item"
                            :label="item"
                            :value="item">
                    </el-option>
                </el-select>
            </template>
            <el-input
                    clearable
                    size="small"
                    class="addInput"
                    v-model="formInline.courseName"
                    suffix-icon="el-icon-search"
                    @keydown.enter.native="init"
                    placeholder="请输入内容"></el-input>
            <el-button size="small" icon="el-icon-search" type="primary"
                       @click="init">搜索
            </el-button>
        </div>
        <div style="margin-top: 10px">
            <el-checkbox-group v-model="checkArr" size="medium">
                <el-col :span=4 v-for="item in optionalColumnList" :key="item.prop">
                    <el-checkbox :label="item.propName" @change="menuChange(item)"></el-checkbox>
                </el-col>
            </el-checkbox-group>
            <el-table
                    :row-key="getRowKeys"
                    :expand-row-keys="expands"
                    style="width: 100%"
                    :data="tableData"
                    @expand-change="selectTeacherById">
                <el-table-column type="expand">
                        <el-tag
                                style="margin-left: 6px" :key="tag.id" v-for="tag in this.rowTeachers"
                                closable
                                :disable-transitions="false"
                                @close="handleCloseTag(tag)" type="success" >{{tag.affiliation}}-{{tag.name}}</el-tag>
                </el-table-column>

                <el-table-column :label="item.propName" :property="item.prop" v-for="(item) in tableColumnList"
                                 :key="item.prop" sortable>

                    <template slot-scope="scope">

                        <span v-if="item.propName==='课程码'||item.propName==='课程名'"><el-tag>{{scope.row[scope.column.property]}}</el-tag></span>
                        <span v-else>{{scope.row[scope.column.property]}}</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="175px">
                    <template slot-scope="scope">
                        <el-button @click="showAddCourseInfo(scope.row)" type="warning" size="mini"
                                   icon="el-icon-plus"></el-button>
                        <el-button type="danger" size="mini"
                                   icon="el-icon-edit"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style="padding-top: 15px"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page.sync="current"
                           :page-sizes="[1, 2, 3, 6, 15]"
                           :page-size="size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="this.total">
            </el-pagination>

            <el-dialog
                    title="为该课程分配教师"
                    :visible.sync="teacherDialogVisible"
                    width="30%">

                <template>
                    <el-select
                            v-model="canTeacherValue"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            placeholder="分配的教师">
                        <el-option
                                v-for="item in teacherOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </template>


                <span slot="footer" class="dialog-footer">
                    <el-button @click="teacherDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addCourseInfo">确 定</el-button>
                  </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    export default {
        name: "CourseManage",
        data() {
            return {
                currentRow :null,
                teacherOptions: [], // 查询教师列表
                canTeacherValue: [],
                teacherDialogVisible: false, // 控制添加教师框
                // 分页
                size: 6,
                current: 1,
                total: 0,
                adminRequest: {
                    name: '',
                    affiliation: '',
                },
                options: ["专业必修课","学科必修课","专业选修课","实践环节"],
                tableData: [],
                formInline: {
                    "courseId": "",
                    "courseName": "",
                    "type": ""
                },
                courseTeacher:{
                    "courseId": "",
                    "id": "",
                    "userId": ""
                },
                tableColumnList:
                    [
                        {prop: 'courseId', propName: '课程码'},
                        {prop: 'courseName', propName: '课程名'},
                        {prop: 'type', propName: '类型'},
                        {prop: 'credit', propName: '学分'},
                    ],
                optionalColumnList:
                    [
                        {prop: 'id', propName: '业务主键'},
                        {prop: 'courseFaculty', propName: '学院'},
                        {prop: 'classNum', propName: '授课班级'},
                        {prop: 'examination', propName: '考核类型'},
                        {prop: 'remark', propName: '备注'},
                    ],
                checkArr: [],
                expands: [],
                getRowKeys(row) {
                    return row.id
                },
                rowTeachers: [],
            }
        },
        mounted() { // 页面加载时
            this.init();
            this.initTeacherOptions();
        },
        methods: {
            handleCloseTag(tag){
                // console.log(this.rowTeachers.indexOf(tag));
                this.rowTeachers.splice(this.rowTeachers.indexOf(tag),1);
                // console.log(tag.id);
                this.$message("删除了"+tag.id+"安全考虑暂不支持");
                // this.deleteRequest('/role/deleteRole/'+tag.id).then(resp=>{
                //     if(resp){
                //         this.$message("删除了"+tag.id);
                //     }
                // })
            },
            selectTeacherById(row, expandedRows){
                this.courseTeacher.courseId = row.courseId;
                var that = this
                if (expandedRows.length) {
                    that.expands = [];
                    this.rowTeachers = [];
                    if (row) {
                        this.postRequest('/course-info/selectUser/1/999',this.courseTeacher).then(resp => {
                            if (resp) {
                                if(resp.data.records.length==0){
                                    this.rowTeachers = [];
                                }else{
                                    this.rowTeachers=(resp.data.records[0].userList);
                                }

                                that.expands.push(row.id)// 每次push进去的是每行的ID
                            }
                        })
                    }
                } else {
                    that.expands = []// 默认不展开
                    this.rowTeachers = [];
                }
            },
            init() {
                this.postRequest('/course/selectCourse/' + this.current + '/' + this.size, this.formInline).then(resp => {
                    // 看一下返回信息
                    console.log(this.formInline);
                    // alert(JSON.stringify(resp));
                    if (resp) {
                        this.tableData = resp.data.records;
                        this.total = resp.data.total;
                    }
                })
            },
            // 分页改变每页数量
            handleSizeChange(size) {
                this.size = size;
                this.init();
            },
            // 分页改变当前页数
            handleCurrentChange(current) {
                this.current = current;
                this.init();
            },
            // 动态表头
            menuChange(item) {
                // 注意  我这里都用的假数据，要从后台获取tableColumnList和dataList的时候
                //，每一次调用menuChange都要重新获取tableColumnList和dataList，保证属性和数据是对应的
                let flag = true
                for (let i = 0; i < this.checkArr.length; i++) {
                    if (this.checkArr[i] === item.propName) {
                        flag = false
                        break
                    }
                }
                if (!flag) {
                    this.tableColumnList.push(item)
                }
                if (flag) {
                    Array.prototype.contains = function (obj) {
                        let j = this.length;
                        while (j--) {
                            if (this[j] === obj) {
                                return j; // 返回的这个 i 就是元素的索引下标，
                            }
                        }
                        return false
                    }
                    this.tableColumnList.splice(this.tableColumnList.contains(item), 1)
                }
            },
            reset() {
                this.formInline.affiliation = null;
                this.formInline.competent = null;
                this.formInline.name = null;
                this.formInline.username = null;
                this.init();
            },
            chang(row) {
                // const _this = this;
                console.log(row.id);
                let enabled = 1;
                if (!row.enabled) {
                    enabled = 0;
                }
                this.putRequest('/admin/updateEnabled', 'id=' + row.id + '&' + 'enabled=' + enabled).then(resp => {
                    if (resp) {
                        console.log(resp);
                    } else {
                        this.$message('失败')
                    }
                })
            },
            handleEdit(index, row) {
                console.log(index, row);
            },
            handleDelete(index, row) {
                console.log(index, row);
            },
            showAddCourseInfo(row){
                this.teacherDialogVisible = true
                this.currentRow = row;
            },
            addCourseInfo() {
                this.teacherDialogVisible = false;
                let ids = '?';
                this.canTeacherValue.forEach(item=>{
                    ids += 'ids='+item + '&';
                });
                this.getRequest('/course-info/addCourseInfo/'+this.currentRow.courseId+'/'+ids).then(resp=>{
                    if(resp){
                        this.canTeacherValue = [];
                    }
                })
            },
            initTeacherOptions(){
                this.getRequest('/admin/selectAllTeacher').then(resp=>{
                    if(resp){
                        this.teacherOptions = resp;
                    }
                })
            }
        }
    }
</script>

<style>
    .addInput {
        width: 300px;
        margin-right: 8px;
    }

    .selectOption {
        margin-right: 8px;
    }
</style>